package com.dm.cloud.configurations.oauth.smspass;

import com.dm.cloud.api.dto.Users;
import com.dm.cloud.databases.redis.JedisUtils;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

@Service
public class SmsCodeUserDetailService {

    public UserDetails loadUserByPhone(String phone, Users users) {
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        //获取验证码
        String smsCode = request.getParameter("smsCode");

        //从redis中获取只当key的值
        String smsStr = JedisUtils.getString("sms"+phone);

        if(StringUtils.isEmpty(smsCode) || !smsCode.equals(smsStr)){
            throw new BadCredentialsException("验证码错误!");
        }

        //验证无误 删除验证码
        JedisUtils.delValue("sms"+phone);
        return new User(users.getUserName(), users.getPassword(), AuthorityUtils.createAuthorityList("ADMIN"));
    }
}